<template>
  <el-form ref="genInfoForm" :model="info" :rules="rules" label-width="150px">
    <el-row>
      <el-col :span="12">
        <el-form-item prop="tplCategory">
          <template #label>生成模板</template>
          <el-select v-model="info.tplCategory" @change="tplSelectChange">
            <el-option label="单表（增删改查）" value="crud" />
            <el-option label="树表（增删改查）" value="tree" />
            <el-option label="主子表（增删改查）" value="sub" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="tplWebType">
          <template #label>前端类型</template>
          <el-select v-model="info.tplWebType">
            <el-option label="Vue2 Element UI 模版" value="element-ui" />
            <el-option label="Vue3 Element Plus 模版" value="element-plus" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="packageName">
          <template #label>
            生成包路径
            <el-tooltip
              content="生成在哪个java包下，例如 com.ruoyi.system"
              placement="top"
            >
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="info.packageName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="moduleName">
          <template #label>
            前端模块名
            <el-tooltip content="前端模块名，用于生成前端代码路径，例如 system" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="info.moduleName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="businessName">
          <template #label>
            生成业务名
            <el-tooltip content="可理解为功能英文名，例如 user" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="info.businessName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="functionName">
          <template #label>
            生成功能名
            <el-tooltip content="用作类描述，例如 用户" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="info.functionName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="genType">
          <template #label>
            生成代码方式
            <el-tooltip
              content="默认为zip压缩包下载，也可以自定义生成路径"
              placement="top"
            >
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-radio v-model="info.genType" value="0">zip压缩包</el-radio>
          <el-radio v-model="info.genType" value="1">自定义路径</el-radio>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item>
          <template #label>
            上级菜单
            <el-tooltip
              content="分配到指定菜单下，例如 系统管理"
              placement="top"
            >
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-tree-select
            v-model="info.parentMenuId"
            :data="menuOptions"
            :props="{
              value: 'menuId',
              label: 'menuName',
              children: 'children',
            }"
            value-key="menuId"
            placeholder="请选择系统菜单"
            check-strictly
          />
        </el-form-item>
      </el-col>

      <el-col :span="24" v-if="info.genType == '1' && !info.separateFrontend">
        <el-form-item prop="genPath">
          <template #label>
            自定义路径
            <el-tooltip
              content="填写磁盘绝对路径，若不填写，则生成到当前Web项目下"
              placement="top"
            >
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="info.genPath">
            <template #append>
              <el-dropdown>
                <el-button type="primary">
                  快速路径选择
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="info.genPath = '/'"
                      >使用智能默认路径</el-dropdown-item
                    >
                    <el-dropdown-item @click="setCurrentProjectPath"
                      >当前项目根目录</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 增强路径配置 -->
    <template v-if="info.genType == '1'">
      <h4 class="form-header">路径配置增强</h4>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="pathMode">
            <template #label>
              路径生成模式
              <el-tooltip content="选择代码生成的路径组织模式" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select
              v-model="info.pathMode"
              placeholder="请选择路径模式"
              @change="pathModeChange"
            >
              <el-option label="微服务模式（默认）" value="microservice" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="separateFrontend">
            <template #label>
              前后端分离
              <el-tooltip
                content="是否将前端代码和后端代码分别生成到不同路径"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-switch v-model="info.separateFrontend" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="info.separateFrontend">
        <el-col :span="12">
          <el-form-item prop="backendPath">
            <template #label>
              后端代码路径
              <el-tooltip content="后端代码生成的专用路径" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-input v-model="info.backendPath" placeholder="后端代码生成路径">
              <template #append>
                <el-button
                  @click="setDefaultBackendPath"
                  type="primary"
                  size="small"
                >
                  默认
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="frontendPath">
            <template #label>
              前端代码路径
              <el-tooltip
                content="前端代码生成的专用路径，默认为平级RuoYi-Vue3目录"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-input
              v-model="info.frontendPath"
              placeholder="前端代码生成路径"
            >
              <template #append>
                <el-button
                  @click="setDefaultFrontendPath"
                  type="primary"
                  size="small"
                >
                  默认
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item prop="modulePath">
            <template #label>
              后端模块名
              <el-tooltip
                content="后端模块名，用于生成后端微服务模块，例如 parking"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-input v-model="info.modulePath" placeholder="后端模块名" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item>
            <template #label>
              预览功能
              <el-tooltip
                content="预览当前配置下的文件生成路径和代码内容"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-button type="primary" @click="previewPath">预览路径</el-button>
            <el-button type="success" @click="refreshPath" style="margin-left: 10px;">刷新预览</el-button>
            <el-button type="warning" @click="previewCode" style="margin-left: 10px;">预览代码</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 路径预览对话框 -->
      <el-dialog v-model="pathPreviewVisible" title="路径预览" width="70%">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="实体类">
            <path-display :path-info="pathPreview.domain" />
          </el-descriptions-item>
          <el-descriptions-item label="控制器">
            <path-display :path-info="pathPreview.controller" />
          </el-descriptions-item>
          <el-descriptions-item label="服务接口">
            <path-display :path-info="pathPreview.service" />
          </el-descriptions-item>
          <el-descriptions-item label="Mapper文件">
            <path-display :path-info="pathPreview.mapper" />
          </el-descriptions-item>
          <el-descriptions-item label="API接口">
            <path-display :path-info="pathPreview.api" />
          </el-descriptions-item>
          <el-descriptions-item label="Vue页面">
            <path-display :path-info="pathPreview.vue" />
          </el-descriptions-item>
          <!-- 微服务模式下显示配置文件 -->
          <el-descriptions-item v-if="pathPreview.pom" label="POM配置">
            <path-display :path-info="pathPreview.pom" />
          </el-descriptions-item>
          <el-descriptions-item v-if="pathPreview.bootstrap" label="Bootstrap配置">
            <path-display :path-info="pathPreview.bootstrap" />
          </el-descriptions-item>
          <el-descriptions-item v-if="pathPreview.application" label="主启动类">
            <path-display :path-info="pathPreview.application" />
          </el-descriptions-item>
        </el-descriptions>

        <!-- 颜色说明 -->
        <div class="path-legend" style="margin-top: 20px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
          <div style="font-weight: bold; margin-bottom: 8px;">路径颜色说明：</div>
          <div style="display: flex; gap: 20px; flex-wrap: wrap;">
            <span><span class="legend-color default-path">■</span> 默认路径（带背景）</span>
            <span><span class="legend-color module-name">■</span> 用户模块名（带背景）</span>
            <span><span class="legend-color business-name">■</span> 业务名称（带背景）</span>
            <span><span class="legend-color standard-path">■</span> 标准路径</span>
          </div>
        </div>
      </el-dialog>

      <!-- 代码预览对话框 -->
      <el-dialog :title="codePreview.title" v-model="codePreviewVisible" width="80%" top="5vh" append-to-body class="scrollbar">
        <el-tabs v-model="codePreview.activeName">
          <el-tab-pane
            v-for="(value, key) in codePreview.data"
            :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
            :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
            :key="value"
          >
            <el-link :underline="false" icon="DocumentCopy" v-copyText="value" v-copyText:callback="copyTextSuccess" style="float:right">&nbsp;复制</el-link>
            <pre>{{ value }}</pre>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </template>

    <template v-if="info.tplCategory == 'tree'">
      <h4 class="form-header">其他信息</h4>
      <el-row v-show="info.tplCategory == 'tree'">
        <el-col :span="12">
          <el-form-item>
            <template #label>
              树编码字段
              <el-tooltip
                content="树显示的编码字段名， 如：dept_id"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select v-model="info.treeCode" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              树父编码字段
              <el-tooltip
                content="树显示的父编码字段名， 如：parent_Id"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select v-model="info.treeParentCode" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              树名称字段
              <el-tooltip
                content="树节点的显示名称字段名， 如：dept_name"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select v-model="info.treeName" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>

    <template v-if="info.tplCategory == 'sub'">
      <h4 class="form-header">关联信息</h4>
      <el-row>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              关联子表的表名
              <el-tooltip
                content="关联子表的表名， 如：sys_user"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select
              v-model="info.subTableName"
              placeholder="请选择"
              @change="subSelectChange"
            >
              <el-option
                v-for="(table, index) in tables"
                :key="index"
                :label="table.tableName + '：' + table.tableComment"
                :value="table.tableName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              子表关联的外键名
              <el-tooltip
                content="子表关联的外键名， 如：user_id"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </template>
            <el-select v-model="info.subTableFkName" placeholder="请选择">
              <el-option
                v-for="(column, index) in subColumns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </el-form>
</template>

<script setup>
import { listMenu } from "@/api/system/menu";
import { pathPreview as getPathPreview, getProjectPaths, previewTable } from "@/api/tool/gen";
import PathDisplay from "./components/PathDisplay.vue";

const subColumns = ref([]);
const menuOptions = ref([]);
const pathPreviewVisible = ref(false);
const pathPreview = ref({});
const projectPaths = ref({});
// 代码预览相关
const codePreviewVisible = ref(false);
const codePreview = ref({
  title: "代码预览",
  activeName: "domain.java",
  data: {}
});
const { proxy } = getCurrentInstance();

const props = defineProps({
  info: {
    type: Object,
    default: null,
  },
  tables: {
    type: Array,
    default: null,
  },
});

const emit = defineEmits(['submitForm', 'saveConfigOnly']);

// 表单校验
const rules = ref({
  tplCategory: [{ required: true, message: "请选择生成模板", trigger: "blur" }],
  packageName: [
    { required: true, message: "请输入生成包路径", trigger: "blur" },
  ],
  moduleName: [
    { required: true, message: "请输入前端模块名", trigger: "blur" },
  ],
  businessName: [
    { required: true, message: "请输入生成业务名", trigger: "blur" },
  ],
  functionName: [
    { required: true, message: "请输入生成功能名", trigger: "blur" },
  ],
});

function subSelectChange(value) {
  props.info.subTableFkName = "";
}

function tplSelectChange(value) {
  if (value !== "sub") {
    props.info.subTableName = "";
    props.info.subTableFkName = "";
  }
}

function setSubTableColumns(value) {
  for (var item in props.tables) {
    const name = props.tables[item].tableName;
    if (value === name) {
      subColumns.value = props.tables[item].columns;
      break;
    }
  }
}

/** 查询菜单下拉树结构 */
function getMenuTreeselect() {
  listMenu().then((response) => {
    menuOptions.value = proxy.handleTree(response.data, "menuId");
  });
}

/** 路径模式变化处理 */
function pathModeChange(value) {
  console.log("路径模式变化：", value);

  // 微服务模式设置默认值
  if (value === 'microservice') {
    if (!props.info.modulePath) {
      props.info.modulePath = props.info.moduleName;
    }
    if (!props.info.separateFrontend) {
      props.info.separateFrontend = true;
    }
    // 微服务模式自动设置默认路径
    setDefaultFrontendPath();
    setDefaultBackendPath();
  }
}

/** 设置当前项目路径 */
function setCurrentProjectPath() {
  if (projectPaths.value.backendPath) {
    props.info.genPath = projectPaths.value.backendPath;
  }
}

/** 设置默认前端路径 */
function setDefaultFrontendPath() {
  if (projectPaths.value.frontendPath) {
    props.info.frontendPath = projectPaths.value.frontendPath;
  }
}

/** 设置默认后端路径 */
function setDefaultBackendPath() {
  if (projectPaths.value.backendPath) {
    props.info.backendPath = projectPaths.value.backendPath;
  }
}

/** 获取项目路径信息 */
function loadProjectPaths() {
  getProjectPaths()
    .then((response) => {
      projectPaths.value = response.data;
    })
    .catch((error) => {
      console.warn("获取项目路径失败：", error);
      // 设置默认值
      projectPaths.value = {
        backendPath: "F:\\wechat\\parking\\RuoYi-Cloud",
        frontendPath: "F:\\wechat\\parking\\RuoYi-Vue3\\src",
        projectRoot: "F:\\wechat\\parking",
      };
    });
}

/** 预览路径 */
function previewPath() {
  if (!props.info.tableId) {
    proxy.$modal.msgError("请先保存表配置信息");
    return;
  }

  getPathPreview(props.info.tableId)
    .then((response) => {
      pathPreview.value = response.data;
      pathPreviewVisible.value = true;
    })
    .catch((error) => {
      proxy.$modal.msgError("获取路径预览失败：" + error.message);
    });
}

/** 刷新预览路径 */
function refreshPath() {
  if (!props.info.tableId) {
    proxy.$modal.msgError("请先保存表配置信息");
    return;
  }

  // 触发保存配置事件，父组件会处理保存逻辑
  emit("saveConfigOnly", previewPath);
}

/** 预览代码 */
function previewCode() {
  if (!props.info.tableId) {
    proxy.$modal.msgError("请先保存表配置信息");
    return;
  }

  previewTable(props.info.tableId)
    .then((response) => {
      codePreview.value.data = response.data;
      codePreview.value.open = true;
      codePreview.value.activeName = "domain.java";
      codePreviewVisible.value = true;
    })
    .catch((error) => {
      proxy.$modal.msgError("获取代码预览失败：" + error.message);
    });
}

/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功");
}

onMounted(() => {
  getMenuTreeselect();
  loadProjectPaths();
});

watch(
  () => props.info.subTableName,
  (val) => {
    setSubTableColumns(val);
  }
);

watch(
  () => props.info.tplWebType,
  (val) => {
    if (val === "") {
      props.info.tplWebType = "element-plus";
    }
  }
);

// 监听前后端分离开关，自动设置默认路径
watch(
  () => props.info.separateFrontend,
  (val) => {
    if (val && !props.info.frontendPath && !props.info.backendPath) {
      setDefaultFrontendPath();
      setDefaultBackendPath();
    }
  }
);
</script>

<style scoped>
/* 路径颜色样式 */
.default-path {
  color: #67c23a; /* 绿色 - 默认路径 */
  font-weight: 500;
}

.module-name {
  color: #409eff; /* 蓝色 - 用户模块名 */
  font-weight: 600;
  background-color: #ecf5ff;
  padding: 1px 4px;
  border-radius: 3px;
}

.business-name {
  color: #e6a23c; /* 橙色 - 业务名称 */
  font-weight: 600;
  background-color: #fdf6ec;
  padding: 1px 4px;
  border-radius: 3px;
}

.standard-path {
  color: #606266; /* 灰色 - 标准路径 */
}

.custom-path {
  color: #f56c6c; /* 红色 - 完全自定义路径 */
  font-weight: 500;
}

/* 图例颜色块 */
.legend-color {
  display: inline-block;
  width: 16px;
  height: 14px;
  margin-right: 6px;
  vertical-align: middle;
  border-radius: 2px;
  border: 1px solid transparent;
}

.legend-color.default-path {
  color: #67c23a;
  background-color: #f0f9ff;
  border-color: #e1f5fe;
}

.legend-color.module-name {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #d4edff;
}

.legend-color.business-name {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #faecd8;
}

.legend-color.standard-path {
  color: #606266;
}

/* 路径显示容器 */
.path-display {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  word-break: break-all;
  white-space: pre-wrap;
}
</style>
